package com.puyuba.puyuba.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.puyuba.puyuba.MainActivity;
import com.puyuba.puyuba.R;
import com.pyb.java.commonutil.activity.ActivityManager;
import com.pyb.java.basemodule.BaseActivity;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.bean.UserInfoBean;
import com.pyb.java.network.NetBaseApi;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.utils.RegularUtils;
import com.pyb.java.commonutil.utils.StringUtil;
import com.pyb.java.commonutil.ToastHelper;
import com.pyb.module.ogin.utils.EaseIMUtils;

import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

public class LoginActivity extends BaseActivity implements View.OnClickListener{

    private EditText mEtPhone;
    private EditText mEtVerify;
    private TextView tvGetCaptcha;
    private ImageView mIvBack;
    private Button mBtnLogin;
    private TextView tvLoginUserAgreement;
    private TextView tvLoginPrivacyPolicy;
    private ImageView ivIsselect;

    private int isgetcode = 1;//判断手机号输入13位之后如果已经发送验证码，文字不变蓝
    private String phone;
    private String inputcode;
    private boolean isselect;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.finishOther(this);

        mIvBack = (ImageView) findViewById(R.id.activity_other_login_back);
        mBtnLogin = (Button) findViewById(R.id.btn_activity_login_login);
        mEtPhone = findViewById(R.id.et_login_phone);
        mEtVerify = findViewById(R.id.et_login_verify_code);
        tvGetCaptcha = findViewById(R.id.tv_login_verify_code);
        tvLoginUserAgreement = (TextView) findViewById(R.id.tv_login_user_agreement);
        tvLoginPrivacyPolicy = (TextView) findViewById(R.id.tv_login_privacy_policy);
        ivIsselect = (ImageView) findViewById(R.id.iv_isselect);

        initListener();
    }

    private void initListener() {
        tvGetCaptcha.setOnClickListener(this);
        mIvBack.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        tvLoginUserAgreement.setOnClickListener(this);
        tvLoginPrivacyPolicy.setOnClickListener(this);
        ivIsselect.setOnClickListener(this);

        //输入密码时如果手机号已经输入 确定按钮变色
        mEtVerify.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!mBtnLogin.getText().toString().trim().equals("")){
                    mBtnLogin.setBackgroundResource(charSequence.length() == 0?R.drawable.bg_64748b_30dp :R.drawable.bg_d7dbe0_30dp);
                    mBtnLogin.setTextColor(charSequence.length() == 0?getResources().getColorStateList(R.color.color_9B):getResources().getColorStateList(R.color.color_004d80));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) { }
        });
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_other_login;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_verify_code:
                checkPhone();
                break;
            case R.id.activity_other_login_back:
                this.finish();
                break;
            case R.id.btn_activity_login_login:
                //验证码登录
                checkcodeinfo();
                break;
            case R.id.iv_isselect:
                isselect = !isselect;
                ivIsselect.setImageResource(isselect ? R.mipmap.icon_select : R.mipmap.icon_unselect);
                break;
            case R.id.tv_login_user_agreement:
                MainWebActivity.startMainWebActivity(LoginActivity.this, NetBaseApi.REGISETPROTOCOLURL,"用户注册协议");
                break;
            case R.id.tv_login_privacy_policy:
                MainWebActivity.startMainWebActivity(LoginActivity.this,NetBaseApi.PRIVACYPOLICY,"隐私政策");
                break;

        }
    }
    //检查验证码登录信息
    private void checkcodeinfo() {

        phone = mEtPhone.getText().toString().replaceAll(" ","").trim();
        inputcode = mEtVerify.getText().toString().trim();
        if(StringUtil.isEmpty(phone)){
            ToastHelper.show("请先输入手机号哦");
            return;
        }if(!RegularUtils.isMobile(phone)){
            ToastHelper.show("手机号格式错误");
            return;
        }if (StringUtil.isEmpty(inputcode)){
            ToastHelper.show("请先输入验证码");
            return;
        }if (!isselect){
            ToastHelper.show("请勾选协议");
            return;
        }

        tosmsLogin(phone,inputcode);
    }


    //验证码登录
    private void tosmsLogin(String mobile,String code) {
        hideKeyboardNoView();//解决华为机型安全键盘遮挡toast
        showLoadingDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("smsCode", code);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);

        RetrofitManger.getInstance().createService(UserApi.class)
                .smslogin(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<UserInfoBean>>applySchedulers())
                .subscribe(new ResponseObserve<UserInfoBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<UserInfoBean> responseEntity) {

                        closeLoadingDialog();
                        UserInfoBean data = responseEntity.getData();

                        //存储用户信息
                        CacheUserInfo.getInstance().saveUserInfo(data);
                        EaseIMUtils.getInstance().signin(data.getUser().getHx_uid(),"123456");
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        //这个标记，将会导致任何用来放置该activity的已经存在的task里面的已经存在的activity先清空，然后该activity再在该task中启动，
                        // 也就是说，**这个新启动的activity变为了这个空task的根activity.所有老的activity都结束掉。该标志必须和FLAG_ACTIVITY_NEW_TASK一起使用。**

                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.putExtra("userbean",data);
                        startActivity(intent);
                        finish();
                        ToastHelper.show( "登录成功");
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        closeLoadingDialog();
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable d) {
                        addDisposable(d);
                    }
                });

    }

    /**
     * 获取短信验证码
     */
    private void checkPhone() {

        if(mEtPhone.getText() == null){
            return;
        }
        phone = mEtPhone.getText().toString().replaceAll(" ","").trim();
        if(StringUtil.isEmpty(phone)){
            ToastHelper.show("请先输入手机号哦");
            return;
        }
        if(!RegularUtils.isMobile(phone)) {
            ToastHelper.show("手机号格式错误");
            return;
        }
        tvGetCaptcha.setEnabled(false);
        CountDownTimer timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                tvGetCaptcha.setText("重新获取"+(l/1000)+"秒");
                tvGetCaptcha.setTextColor(getResources().getColorStateList(R.color.color_c2c2c8));
                isgetcode = 2;
            }

            @Override
            public void onFinish() {
                tvGetCaptcha.setEnabled(true);
                tvGetCaptcha.setText("重新获取");
                tvGetCaptcha.setTextColor(getResources().getColorStateList(R.color.color_ffbd00));
                isgetcode = 1;
            }
        };
        timer.start();
        getIdencode(phone);

    }

    private void getIdencode(String cellphone){
        RetrofitManger.getInstance().createService(UserApi.class)
                .getCellPhoneCode(cellphone)
                .compose(RxSchedulers.<ResponseEntity<Object>>applySchedulers())
                .subscribe(new ResponseObserve<Object>() {

                    @Override
                    public void onSuccess(ResponseEntity<Object> responseEntity) {

                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable disposable) {
                        addDisposable(disposable);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        closeLoadingDialog();
                    }
                });
    }


}
